package com.linran.wxpublic.controller;

import com.linran.wxpublic.util.WxUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.util.CollectionUtils;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Collection;
import java.util.UUID;

/**
 * 文件上传接口
 *
 * @author lin
 * @date 2020-08-19 17:13
 */
@Slf4j
@RequestMapping("upload")
@RestController
public class UploadController {

    @Autowired
    private WxUtil wxUtil;

    public static final String WX_MATERIAL_URL = "https://api.weixin.qq.com/cgi-bin/media/upload?access_token=%s&type=%s";
    private RestTemplate restTemplate = new RestTemplate();

    /**
     * 调用微信接口上传临时素材
     *
     * @return
     */
    @PostMapping("/wx/temp/material")
    public Object uploadTempMaterial(@RequestParam("file") MultipartFile multipartFile,
                                     @RequestParam("fileType") String fileType) throws IOException {
        File tempFile = null;
        try {
            //文件预处理
            tempFile = new File(UUID.randomUUID().toString().replaceAll("-", "")+multipartFile.getOriginalFilename()
                    .substring(multipartFile.getOriginalFilename().lastIndexOf("."))).getAbsoluteFile();
            File parentFile = tempFile.getParentFile();
            if (!parentFile.exists()) {
                parentFile.mkdirs();
            }
            multipartFile.transferTo(tempFile);
            log.info("[临时文件]  地址：{}", tempFile.getAbsolutePath());
            FileSystemResource fileSystemResource = new FileSystemResource(tempFile);

            //设置请求头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.MULTIPART_FORM_DATA);

            //设置请求体，注意是LinkedMultiValueMap
            MultiValueMap<String, Object> form = new LinkedMultiValueMap<>();
            form.add("media", fileSystemResource);

            //用HttpEntity封装请求报文
            HttpEntity<MultiValueMap<String, Object>> files = new HttpEntity<>(form, headers);
            String url = String.format(WX_MATERIAL_URL, wxUtil.getWxToken(), fileType);
            log.info("[微信临时素材上传] url:{}", url);

            return restTemplate.postForEntity(url, files, String.class);
        } finally {
            //删除临时文件
            if (tempFile != null && tempFile.exists()) {
                boolean delete = tempFile.delete();
                log.info("[临时文件] fileName:{} 删除结果:{}", tempFile.getName(), delete);
            }
        }
    }

    @PostMapping("/material")
    public Object uploadMaterial(@RequestParam("files") Collection<MultipartFile> files) {
        if (!CollectionUtils.isEmpty(files)) {
            files.forEach(file->{
                System.out.printf("文件名:%s 文件mimeType:%s %n", file.getOriginalFilename(), file.getContentType());
            });
        }
        return "deal success";
    }
}
